/*
 * @author ${user}
 * @date ${year}-${month}-${day}
 */

package net.xdclass.component;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import net.minidev.json.JSONUtil;
import net.xdclass.config.WechatPayApi;
import net.xdclass.config.WechatPayConfig;
import net.xdclass.enums.ProductOrderPayTypeEnum;
import net.xdclass.util.CommonUtil;
import net.xdclass.vo.PayInfoVO;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@Slf4j
@Component
public class WechartPayStrategy implements  PayStrategy{
	@Autowired
	private CloseableHttpClient wechatPayClient;
	@Autowired
	private WechatPayConfig payConfig;

	@Override
	public String getType() {
		return ProductOrderPayTypeEnum.WECHAT_APY.name();
	}

	@Override
	public String unifiedOrder(PayInfoVO payInfoVO) {
		String outTradeNo = payInfoVO.getOutTradeNo();
		JSONObject payObj = new JSONObject();
		payObj.put("mchid", payConfig.getMchId());
		payObj.put("out_trade_no", outTradeNo);
		payObj.put("appid", payConfig.getWxPayAppid());
		payObj.put("description", "小滴课堂海量数据项目大课");
		payObj.put("notify_url", payConfig.getCallbackUrl());
		int amount = payInfoVO.getPayFee().multiply(BigDecimal.valueOf(100)).intValue();
		JSONObject amountObj = new JSONObject();
		amountObj.put("total", amount);
		amountObj.put("currency", "CNY");
		payObj.put("amount", amountObj);

		//附属参数，可以用在回调
		payObj.put("attach", "{\"accountNo\":" + 888 + "}");

		String body = payObj.toJSONString();
		log.info("消息主体${}", body);

		StringEntity entity = new StringEntity(body, "utf-8");
		entity.setContentType("application/json");

		HttpPost httpPost = new HttpPost(WechatPayApi.NATIVE_ORDER);
		httpPost.setHeader("Accept", "application/json");
		httpPost.setEntity(entity);

		String result = "";
		try (CloseableHttpResponse response = wechatPayClient.execute(httpPost)) {
			int statusCode = response.getStatusLine().getStatusCode();
			String responseStr = EntityUtils.toString(response.getEntity());
			if (statusCode == HttpStatus.SC_OK){
               JSONObject object = JSONObject.parseObject(responseStr);
               if(object.containsKey("code_url")){
               result = object.getString("code_url");
               }
			}
			log.info("下单响应码:{},响应体:{}", statusCode, responseStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public String refund(PayInfoVO payInfoVO) {
		return null;
	}

	@Override
	public String queryPayStatus(PayInfoVO payInfoVO) {
		String outTradeNo = payInfoVO.getOutTradeNo();
		String url = String.format(WechatPayApi.NATIVE_QUERY,outTradeNo,payConfig.getMchId());
		HttpGet httpGet = new HttpGet(url);
		httpGet.setHeader("Accept","application/json");
		String result="";
		try (CloseableHttpResponse response = wechatPayClient.execute(httpGet)) {
			int statusCode = response.getStatusLine().getStatusCode();
			String responseStr = EntityUtils.toString(response.getEntity());
			if (statusCode == HttpStatus.SC_OK){
				JSONObject jsonObject = JSONObject.parseObject(responseStr);
				if(jsonObject.containsKey("trade_state")){
					result = jsonObject.getString("trade_state");
				}
			}
			log.info("下单响应码:{},响应体:{}", statusCode, responseStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public String closeOrder(PayInfoVO payInfoVO) {
		String outTradeNo = payInfoVO.getOutTradeNo();
		JSONObject closeJson = new JSONObject();
		closeJson.put("out_trade_no",outTradeNo);
		String closeString= closeJson.toJSONString();
		StringEntity stringEntity = new StringEntity(closeString,"UTF-8");
		HttpPost httpPost = new HttpPost(WechatPayApi.NATIVE_CLOSE_ORDER);
		httpPost.setEntity(stringEntity);
		httpPost.setHeader("Accept","application/json");
		String result = "close_fail";
		try(CloseableHttpResponse response = wechatPayClient.execute(httpPost)){
			int statusCode = response.getStatusLine().getStatusCode();
			String responseStr = EntityUtils.toString(response.getEntity());
			if(statusCode == HttpStatus.SC_NO_CONTENT){
				result = "close_success";
			}
			log.info("下单响应码:{},响应体:{}", statusCode, responseStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
